package K次取反后最大化的数组和;

import java.util.Arrays;

class Solution {
    public int largestSumAfterKNegations(int[] nums, int k) {
        int n = nums.length, min = 0x3f3f3f3f, sum = 0, m = 0;
        for (int i = 0; i < n; i++) {
            if (nums[i] < 0) {
                m++;
            }
            min = Math.min(min, Math.abs(nums[i]));
        }
        if (m >= k) {
            Arrays.sort(nums);
            for (int i = 0; i < k; i++) {
                sum += Math.abs(nums[i]);
            }
            for (int i = k; i < n; i++) {
                sum += nums[i];
            }
        } else {
            for (int i = 0; i < n; i++) {
                sum += Math.abs(nums[i]);
            }
            if ((k - m) % 2 == 1) {
                sum -= 2 * min;
            }
        }
        return sum;
    }
}